package cn.rengy.web.framework.wxmp.wxmenu;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

import cn.rengy.lang.WeChatException;
import cn.rengy.tpa.wxmp.menu.MenuManager;
import cn.rengy.tpa.wxmp.token.AccessToken;
import cn.rengy.web.framework.constants.Constants;

import cn.rengy.web.framework.sql.DbService;
import cn.rengy.web.framework.wxmp.token.AccessTokenCacheService;
/**
 *
 */
@Service
public class WxMenuService {
	@Autowired
	private DbService dbService;
	@Autowired
	private AccessTokenCacheService accessTokenCacheService;
	private static Logger logger = LoggerFactory.getLogger(WxMenuService.class);
	/**
	 * 立即生效默认菜单
	 * @param paramMap
	 * @throws WeChatException 
	 * @throws Exception 
	 */
	public void takeEffectDefault(Map<String,Object> paramMap) throws Exception {
		Object id=paramMap.get("id");
		String appid=MapUtils.getString(paramMap, "appid");
		AccessToken accessToken=accessTokenCacheService.getAccessToken(appid);
		List<Map<String,Object>> menuList=queryMenuItem(appid,id,null);
		if(menuList!=null){
			Map<String,Object> menu=new HashMap<String,Object>();
			menu.put("button", menuList);
			String menuJson=JSON.toJSONString(menu);
			if(logger.isDebugEnabled()){
				logger.debug("菜单内容："+menuJson);
			}
			MenuManager menuManager=new MenuManager(accessToken);
			menuManager.create(menuJson);
		}else{
			throw new Exception("菜单内容为空！");
		}
	}
	
	private List<Map<String,Object>> queryMenuItem(String appid,Object menuId,Object parentId) throws Exception{
		List<Map<String,Object>> list=null;
		if(parentId==null){
			list=this.dbService.queryForList(false,"select_menu_item_null_parent_id", menuId);
		}else{
			list=this.dbService.queryForList(false,"select_menu_item_by_parent_id",parentId, menuId);
		}
		if(list!=null){
			for(Map<String,Object> map:list){
				String type=(String)map.get("type");
				Object id=map.remove("uuid");
				//String is_oauth=(String)map.remove("is_oauth");
				//String scope=(String)map.remove("scope");
				//String scope="snsapi_base";
				/*Long page_id=(Long)map.remove("page_id");
				if("view".equals(type)){//跳转URL事件
					if(page_id>0){//跳转页面
						Map<String,Object> wxpage=this.dbService.queryForMap(false,"select_get_company_wx_page2", page_id);
						String url=(String)wxpage.get("access_url");
						if(url.startsWith("http")){
							map.put("url", url);
						}else{
							map.put("url", propertyService.getProperty("domain")+url);
						}
					}else{
						throw new Exception("选择了view事件但跳转页面为空！");
					}
				}*/
				map.put("sub_button", queryMenuItem(appid,menuId,id));
			}
		}
		return list;
	}
}
